package com.jiyici.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jiyici.ItemHolder;
import com.jiyici.R;
import com.jiyici.data.ClientDBHelper;
import com.jiyici.model.Item;
import com.jiyici.model.ModelUtil;
import com.jiyici.model.Record;
import com.jiyici.utils.DateUtil;
import com.squareup.timessquare.CalendarPickerView;
import com.squareup.timessquare.YearView;

public class RecordCalendarFragment extends BaseFragment {

    private ArrayList<Record> mRecordList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_record_calendar, container, false);
        showYear(view);
        showMonth(view);
        return view;
    }
    
    private void showYear(View view) {
        final YearView yearView = (YearView) view.findViewById(R.id.year_view);
        yearView.setYear(2014);
    }
    
    private void showMonth(View view) {
        final CalendarPickerView calendar = (CalendarPickerView) view.findViewById(R.id.calendar_view);
        calendar.init(new Date(), new Date());
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                mRecordList = ClientDBHelper.getInstance().dbQueryRecord(getItem().getId());
                ModelUtil.sordRecord(mRecordList, null, ModelUtil.SORT_DESC);
                calendar.setCountMaps(DateUtil.calculateDayCount(mRecordList));
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                int size = mRecordList.size();
                if (size == 0) {
                    /* display empty view */
                    return;
                }
                
                Record lastestRecord = mRecordList.get(0);
                Calendar minC = Calendar.getInstance();
                minC.setTimeInMillis(lastestRecord.recordTime);
                minC.set(Calendar.DATE, 1);
                
                Calendar maxC = Calendar.getInstance();
                maxC.setTimeInMillis(lastestRecord.recordTime);
                maxC.set(Calendar.DATE, minC.getActualMaximum(Calendar.DATE));
                
                
                calendar.init(minC.getTime(), maxC.getTime());
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

        }.execute();
    }

    private Item getItem() {
        return ((ItemHolder) getActivity()).getItem();
    }
}
